using CodeGame.HostingStartup;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TestWebApi;
Environment.SetEnvironmentVariable("SkyWalking:ServiceName", $"{Environment.GetEnvironmentVariable("CG_UserName")}::WebApi");
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers(options => options.Filters.Add<SkywalkingLogFilter>())
    .ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = context =>
        {
            var message = context.ModelState.First().Value.Errors.First().ErrorMessage;
            return new BadRequestObjectResult(message);
        };
    });
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var password = Environment.GetEnvironmentVariable("CG_UserPassword");
var username = Environment.GetEnvironmentVariable("CG_UserName");
var connectionString = Environment.GetEnvironmentVariable("ASPNETCORE_CONNECTIONSTRING");
connectionString = connectionString.Replace("{password}", password).Replace("{username}", username);
Console.WriteLine(connectionString);
builder.Services.AddDbContext<TestDbContext>(options =>
{
    options.UseNpgsql(connectionString);
});
var redisConnectionString = Environment.GetEnvironmentVariable("ASPNETCORE_REDISCONNECTIONSTRING");
redisConnectionString = redisConnectionString.Replace("{password}", password).Replace("{username}", username);
Console.WriteLine(redisConnectionString);
builder.Services.AddScoped(sp => new FreeRedis.RedisClient(redisConnectionString));
var app = builder.Build();
using var scope = app.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<TestDbContext>();
dbContext.Database.Migrate();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseAuthorization();

app.MapControllers();
app.Run();
